from flask import Flask, request, jsonify
from http import HTTPStatus
from dashscope import Generation
import dashscope
import threading

app = Flask(__name__)

def process_message(messages):
    processed_messages = []
    for message in messages:
        role = message.get('role')
        content = message.get('content')
        if role and content:
            processed_messages.append({'role': role, 'content': content})
    return processed_messages

@app.route('/api/ask', methods=['POST'])

def ask_question():
    data = request.get_json()
    api_key = data.get('api_key')  # 将 YOUR_API_KEY 改成您创建的 API-KEY
    message_json = data.get('message_json')

    if not api_key or not message_json:
        return jsonify({'error': 'Missing required parameters'}), 400
    
    dashscope.api_key = api_key

    messages = process_message(message_json)
    
    response = Generation.call(
        # Generation.Models.qwen_turbo,
        'qwen1.5-72b-chat',
        messages=messages,
        result_format='message',  # 设置结果为消息格式
    )
    
    if response.status_code == HTTPStatus.OK:
        response_message = response
    else:
        error_message = {'error': 'Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        )}
        return jsonify(error_message), 500

    return jsonify({'response': response_message})

def run_flask_app(host, port):
    app.run(host=host, port=port)

if __name__ == '__main__':
    ips_and_ports = {
        '127.0.0.1': 5000,
        '0.0.0.0': 5001,
        '192.168.6.66': 8101
    }

    threads = []
    for ip, port in ips_and_ports.items():
        thread = threading.Thread(target=run_flask_app, args=(ip, port))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()
